// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later
package xyz.apiote.bimba.czwek.journeys

import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import org.openapitools.client.infrastructure.ServerException
import xyz.apiote.bimba.czwek.data.traffic.Place
import xyz.apiote.bimba.czwek.repo.Journey
import xyz.apiote.bimba.czwek.repo.JourneyParams
import java.net.SocketTimeoutException

class JourneysViewModel : ViewModel() {

	private val _journeys = MutableLiveData<List<Journey>>()
	val journeys: LiveData<List<Journey>> = _journeys

	fun getJourneys(context: Context, origin: Place, destination: Place, params: JourneyParams) {
		viewModelScope.launch {
			try {
				_journeys.value =
					xyz.apiote.bimba.czwek.api.getJourney(origin, destination, params, context)
			} catch (e: SocketTimeoutException) {
				_journeys.value = emptyList<Journey>()
				Log.e("Journeys", "timeout: $e")
			} catch (e: ServerException) {
				_journeys.value = emptyList<Journey>()
				Log.w("Suggestion", "Transitous returned: ${e.statusCode}, ${e.message}")
			} catch (e: Exception) {
				_journeys.value = emptyList<Journey>()
				Log.w("Suggestion", "Exception: $e")
			}
		}
	}
}
